package com.deke.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：Username 刘亦辰（59372312@qq.com）
 * @date ：Created in 2022/11/2 15:39
 * @description：JWT 工具类
 * @modified By：
 * @version:
 */
public class JwtTool {
        private static String sign = "com.deke";

        /**
        * @create by: Username 刘亦辰 
        * @description: 生成JWT加密字符串 
        * @create time: 2022/11/2 15:40
        * @param null
        * @return :  
        */
        public static String createJWT(Map<String,Object> map){
            //定义信息
            Map<String,Object> head = new HashMap<>();
            head.put("alg","HS256");
            head.put("typ","JWT");
            //定义颁发时间
            Date iat = new Date();
            Calendar expire = Calendar.getInstance();
            expire.set(Calendar.SECOND,7200);
            Date expireTime = expire.getTime();

            String token = JWT.create()
                    //头信息
                    .withHeader(head)
                    //颁发时间
                    .withIssuedAt(iat)
                    //设置过期时间
                    .withExpiresAt(expireTime)
                    //自定义内容
                    .withClaim("userInfo",map)
                    //签名
                    .sign(Algorithm.HMAC256(com.deke.utils.JwtTool.sign));
            return token;
        }

        /**
        * @create by: Username 刘亦辰 
        * @description: 校验token是否通过 
        * @create time: 2022/11/2 16:09
        * @param null
        * @return :  
        */
        public static boolean verifyToken(String token){
            JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
            try {
                DecodedJWT verify = build.verify(token);
                System.out.println("token通过");
                return true;
            }catch (Exception e){
                System.out.println("token无效");
                return  false;
            }
        }

    /**
    * @create by: Username 刘亦辰 
    * @description: 获取token中的用户信息 
    * @create time: 2022/11/2 16:12
    * @param null
    * @return :  
    */
    public static Map<String,Object> getTokenClaim(String token){
        JWTVerifier build = JWT.require(Algorithm.HMAC256(sign)).build();
        DecodedJWT verify = build.verify(token);
        Claim username = verify.getClaim("userInfo");
        return username.asMap();
    }


}